#!/usr/bin/perl
# $Id$
# Author: Charles Mauch (cmauch@gmail.com)
# Description: Randomized Evolution Backgrounds based on time of day
# Legal: (c) 2006 Charles Mauch, released under the terms of the GPLv2 (or later)

# -- [ meta information ] ----------------------------------------------------
#
# * Changes backgrounds every time called using eesh.  This keeps eterms
#   happy.  Optionally sets root hints so aterms/etc stay happy too.
#
# * Autodetects the number of virtual desktops, and applies a different 
#   background to each desktop!
#
# Assumptions:
#  * One argument is passed to the script, the subdirectory containing the
#    images you wish to use.
#  * Called from crontab, a typical entry would look like:
#    */10 1,2,3,4 * * *       DISPLAY=:0.0 ~/bin/randgnome.pl earlymorning
#    where earlymoring is a valid subdirectory in the backgrounds directory
#  * Touching a file called "stop" in the background directory stops background
#    randomization.
#  * Requires updated Eesh.pm.  .003 from cpan will not work with e0.16.8, but
#    this script will work with e0.16.7.  Update Eesh.pm with the proper commands
#    if you want to use this on e0.16.8
#
# -- [ bugs ] ----------------------------------------------------------------
#
#  * composite settings aren't reapplied on background change until you switch
#    to a different desktop, then back.  e0.16.8 bug?
#
#  * Currently assumes that your background category directory is five subdirs
#    deep.  ADJUST THE SPLIT LINE BELOW if this is not the case.  Eg, on my
#    system the layout looks like:
#    /home/cmauch/.e16/backgrounds/CATEGORY/background.png   
#    The backgrounds dir is a symlink to my existing .backgrounds directory
#    in my home.
#    

$stoprand = "/home/cmauch/.backgrounds/stop";
if (-f "$stoprand") { 
        exit; 
}

use Eesh qw( :all ) ;
e_open() ;

my $grabvirt = e_recv( 'num_desks ?');
$grabvirt =~ /Number\sof\sDesks:\s(.*)/;
$virtwindows = $1;
my $virtcount = 0;

my @selected = undef;
my @backgrounds = e_backgrounds();
my $input = @ARGV[0];

foreach my $item (@backgrounds) {
 my $bgfile = e_background($item)->{'bg.file'};
 ($root, $sub1, $sub2, $sub3, $sub4, $category)= split(/\//,$bgfile);
 
 if ($category eq $input) {
  push (@selected, $item);
 } 
}

while ($virtcount < $virtwindows) {
 e_send("background use @selected[getrand($#selected-1)] $virtcount");
 $virtcount ++;
}

sub getrand {
 my $num = $_[0];
 my $tmp = int(rand($num)+1);
 return($tmp);
}

#e_send("hints xroot root");
